package xjh.him.adapter;

import android.widget.ImageView;
import android.widget.TextView;

import com.xjh.him.R;

import java.util.HashSet;
import java.util.List;

import xjh.him.bean.MsgBean;
import xjh.him.common.MyBaseAdapter;
import xjh.him.common.MyViewHolder;
import xjh.him.common.SharedData;
import xjh.him.entity.ChatMsg;
import xjh.him.util.GlideUtil;
import xjh.him.util.LogcatUtil;

public class MsgListAdapter extends MyBaseAdapter<MsgBean> {
    private List<MsgBean> beans;
    private HashSet<Integer> chatterSet;

    public MsgListAdapter(List<MsgBean> beans, int layoutRes, HashSet<Integer> chatterSet) {
        super(beans, layoutRes);
        this.beans = beans;
        this.chatterSet = chatterSet;
    }

    @Override
    public void bindView(MyViewHolder holder, MsgBean bean) {
        ImageView avatar = holder.getItemView().findViewById(R.id.item_avatar);
        TextView name = holder.getItemView().findViewById(R.id.item_name);
        TextView footText = holder.getItemView().findViewById(R.id.item_foot_text);

        GlideUtil.loadImage(holder.getItemView().getContext(), bean.getChat().getChatAvatar(),
                avatar, GlideUtil.defaultRoundedAvatarOpt());
        name.setText(bean.getChat().getName());

        StringBuilder builder = new StringBuilder();
        if (bean.getChatMsg() != null) {
            if (SharedData.me.getId().intValue() != bean.getChatMsg().getUserId().intValue()) {
                builder.append(bean.getChat().getName()).append("：");
            }

            if (bean.getChatMsg().getType() == SharedData.CHAT_MSG_TYPE_TEXT) {
                builder.append(bean.getChatMsg().getContent());
            }else if (bean.getChatMsg().getType() == SharedData.CHAT_MSG_TYPE_IMAGE) {
                builder.append("[图片]");
            }
        }
        footText.setText(builder.toString());
    }

    public HashSet<Integer> getChatterSet() {
        return chatterSet;
    }

    public List<MsgBean> getBeans() {
        return beans;
    }

    public void updateItem(ChatMsg chatMsg) {
        MsgBean msgBean = null;
        for (MsgBean bean : beans) {
            if (bean.getChat().getId().intValue() == chatMsg.getChatId().intValue()) {
                msgBean = bean;
                break;
            }
        }
        if (msgBean != null) {
            msgBean.setChatMsg(chatMsg);
            notifyDataSetChanged();
            LogcatUtil.d("update msg item foot_text: %s", chatMsg.getContent());
        }else {
            LogcatUtil.w("chat_id:%d not exist", chatMsg.getChatId());
        }
    }
}
